import { api } from "@/global/utils/api";
import useApiPromiseHandler from "./api-promise-handler";
import { useI18n } from "vue-i18n";

export default function useTranslationAPI() {
  const { t } = useI18n();
  const translate = (text) => new Promise<string>((resolve, reject) => {
    text = text.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "");
    useApiPromiseHandler(t, 
      api.get(`/translate/${text}`),
      (data=>{
        const result = JSON.parse(data.data);
        if (result.translateResult && result.translateResult.length > 0) {
          let transText = '';
          result.translateResult[0].forEach(s => {
            transText += s.tgt;
          });
          resolve(transText);
        } else {
          reject('没有翻译结果');
        }
      }),
      reject
    )
  })

  return { translate };
}